package com.xcode.luckymoney;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.List;
import java.util.Optional;

/**
 * @author com.ymy.hadoop
 * @date 2019/4/20 23:33
 */
@RestController
public class LuckymoneyController {

    @Autowired
    private LuckymoneyRepository repository;

    @Autowired
    private LuckymoneyService service;

    /***
     * 一次创建两个红包，模拟事务处理
     */
    @PostMapping("/luckymoneys/two")
    public void createTwo(){
        service.createTwo();
    }

    /***
     *  获取红包列表
     */
    @GetMapping("/luckymoneys")
    public List<Luckymoney> list(){
        return repository.findAll();
    }

    /***
     * 创建红包(发红包)
     */
    @PostMapping("/luckymoneys")
    public Luckymoney create(@RequestParam("producer") String producer,
                             @RequestParam("money") BigDecimal money){
        Luckymoney luckmoney = new Luckymoney();
        luckmoney.setProducer(producer);
        luckmoney.setMoney(money);
        return repository.save(luckmoney);
    }

    /**
     * 通过id查询红包
     */
    @GetMapping("/luckymoneys/{id}")
    public Luckymoney findById(@PathVariable("id") Integer id){
       return repository.findById(id).orElse(null);
    }

    /**
     * 更新红包(领红包)
     */
    @PutMapping("/luckymoneys/{id}")
    public Luckymoney update(@PathVariable("id") Integer id,
                             @RequestParam("consumer") String consumber){

        // 判断数据库里面是否有该id，有则拿到该id的一行数据，对id、consumer进行更新
        // 没有则返回null
        Optional<Luckymoney> optional = repository.findById(id);
        if (optional.isPresent()){
            Luckymoney luckmoney = optional.get();
            luckmoney.setId(id);
            luckmoney.setConsumer(consumber);
            return repository.save(luckmoney);
        }
        return null;
    }

}
